<?php
/*
* 文件名: api_caipiao.php
* 作者  : Yoby 微信logove email:logove@qq.com
* 日期时间: 2019/6/13  22:35
* 功能  :彩票功能抓取接口,数据来自500万
 * 支持类型
 {
"ssq":"双色球",
"sd":"福彩3D",
"qlc":"七乐彩",
"pls":"排列三",
"plw":"排列五",
"dlt":"超级大乐透",
"qxc":"七星彩",
"eexw":"22选5",
"bjssxq":"北京33选7"
}地方彩最后两个 可定制抓取
 * 期数查询 api_caipiao.php?s=1&n=30&type=ssq  n表示查询多少期 s=1表示查期数 type=ssq查找类型
 * 数据查询 api_caipiao.php?s=2&type=ssq&q=19067  s=2 表示查数据 type=ssq查找类型 q=19067 查找的期数,不填写这个参数将获取最新一期,用于每天更新
 *
*/
set_time_limit (0);
header("Content-Type:text/html;charset=UTF-8");
if (!function_exists('dump')) {
    function dump($arr){
        echo '<pre>'.print_r($arr,TRUE).'</pre>';
    }
}
/*
 * 设置缓存
 * $name 缓存名称
 * $value 缓存值,可以是数组字符
 * $expire 过期时间
 * */
function setcache($name, $value, $expire = 7000)
{
    $filename = "./{$name}_cache.php";
    $json = json_encode(array($name=>$value,"expire"=>time()+$expire));
    $result = file_put_contents($filename,$json);
    if ($result) {
        return true;
    }
    return false;
}
/*
 * 获取缓存
 * */
function getcache($name)
{
    $filename = "./{$name}_cache.php";
    if (!is_file($filename)) {
        return false;
    }
    $content = file_get_contents($filename);

    $arr = json_decode($content,true);
    if($arr['expire'] <= time())
    {
        return false;
    }
    return $arr["$name"];
}
/*返回ajax状态*/
function json($code=200,$message='请求成功',$list=array(),$total=0){
    $json = array(
        'code'=>$code,
        'msg'=>$message
    );
    if(!empty($list)){
        $json['list'] = $list;
    }
    if(!empty($total)){
        $json['total'] = $total;
    }

    header('Content-type: application/json');
    exit(json_encode($json,JSON_UNESCAPED_UNICODE));
}
/*获取html并用正则处理*/
function get_content($url){
    //$html = file_get_contents($url);
    $html = file_get_contents("compress.zlib://".$url);
    $code= mb_detect_encoding($html, array("GB2312","GBK",'UTF-8','BIG5'));//获取编码
    if($code!="UTF-8"){
        $htmls =  mb_convert_encoding($html, "UTF-8", $code);//转换内容为UTF-8编码
    }else{
        $htmls = $html;
    }
    $htmls = preg_replace("/<script[\s\S]*?<\/script>/i","",$htmls,-1);//去除script
    $htmls = preg_replace("/<noscript[\s\S]*?<\/noscript>/i","",$htmls,-1);//去除noscript
    $htmls=preg_replace("/<(\/?link.*?)>/si","",$htmls);//去掉link
    $htmls=preg_replace("/<(style.*?)>(.*?)<(\/style.*?)>/si","",$htmls);//去掉style
    $htmls =preg_replace("/style=.+?['|\"]/i",'',$htmls,-1);//去除style行内样式
    $htmls =preg_replace('#<!--[^\!\[]*?(?<!\/\/)-->#' , '' , $htmls);//去掉html注释
    //$htmls = preg_replace("/<a[^>]*>(.*?)<\/a>/is", "$1", $htmls);//去除外站超链接
    $htmls =  preg_replace("/(\n\r)/i", '', $htmls); //去掉空行
    $htmls =  preg_replace("/<(input|textarea|select).*?>/i", '', $htmls); //去掉input/textarea/select
    return $htmls;
}
function trimstr($str)
{
    $str = trim($str);
    $str = preg_replace("/\t/","",$str);
    $str = preg_replace("/\r\n/","",$str);
    $str = preg_replace("/\r/","",$str);
    $str = preg_replace("/\n/","",$str);
    $str = preg_replace("/ /","",$str);
    return trim($str); //返回字符串
}
/*表格转数组*/
function tableArr($table)
{
    $table = preg_replace("'<table[^>]*?>'si", "", $table);
    $table = preg_replace("'<tr[^>]*?>'si", "", $table);
    $table = preg_replace("'<td[^>]*?>'si", "", $table);
    $table = str_replace("</tr>", "{tr}", $table);
    $table = str_replace("</td>", "{td}", $table);
    //去掉 HTML 标记
    $table = preg_replace("'<[/!]*?[^<>]*?>'si", "", $table);
    //去掉空白字符
    $table = preg_replace("'([rn])[s]+'", "", $table);
    $table = preg_replace('/&nbsp;/', "", $table);
    $table = str_replace(" ", "", $table);
    $table = str_replace(" ", "", $table);
    $table = str_replace("\r", "", $table);
    $table = str_replace("\t", "", $table);
    $table = str_replace("\n", "", $table);
    $table = explode('{tr}', $table);
    array_pop($table);
    foreach ($table as $key => $tr) {
        $td = explode('{td}', $tr);
        array_pop($td);
        $td_array[] = $td;
    }
    return $td_array;
}
function xml2arr($xml) {
    if (empty($xml)) {
        return array();
    }
    $result = array();
    $xmlobj = simplexml_load_string($xml);
    if($xmlobj instanceof \SimpleXMLElement) {
        $result = json_decode(json_encode($xmlobj), true);
        if (is_array($result)) {
            return $result;
        } else {
            return array();
        }
    } else {
        return $result;
    }
}
function get_qishu($name='ssq',$number='30'){//获取期数

    if(in_array($name,['eexw','bjssxq'])){
        $file=get_content("http://kaijiang.500.com/static/info/kaijiang/xml/$name/list.xml");
       $xml=xml2arr($file);
        $arr1 = array_slice($xml['row'],0,$number);
        foreach ($arr1 as $k=>$v){
          $arr[]=$v['@attributes']['expect'];
        }
    }else{
        $html = get_content("http://kaijiang.500.com/$name.shtml");
        preg_match('/<div class="iSelectList">([\s\S]*?)<\/div>/',$html,$rs);
        preg_match_all('/<a[^>]*>(.*?)<\/a>/is',$rs[1],$rss);
        $arr = array_slice($rss[1],0,$number);
    }

    return $arr;
}

function get_data($name='ssq',$qi="19067")
{
    $url = "http://kaijiang.500.com/shtml/$name/$qi.shtml";
    $html = get_content($url);
    preg_match('/class="kj_tablelist02"([\s\S]*?)<h1>/', $html, $rs);
    if($name=='qxc'){
        preg_match('/class="kj_tablelist02"([\s\S]*?)<div class="kjxq_new_box01">/', $html, $rs);
    }

    //dump($rs);
    preg_match_all('/\d{4}年\d{1,2}月\d{1,2}日/',$rs[1],$rs1);

    preg_match('/<div class="ball_box01">([\s\S]*?)<\/div>/', $rs[1], $rs2);
    preg_match_all('/\d+/',$rs2[1],$rs2);

    preg_match_all('/<span[^>]*>([\s\S]*?)<\/span>/is',$rs[1],$rs3);

    $arr['qishu']=$qi;
    $arr['type']=$name;
    $arr['k_date']=$rs1[0][0];
    $arr['d_date']=$rs1[0][1];
    $arr['haoma']=$rs2[0];
    preg_match_all('/<table[^>]*>([\s\S]*?)<\/table>/', $rs[1], $rs1);
    $kj = tablearr($rs1[0][1]);

    $arr['money'] = $rs3[1][2];
    $arr['money2'] = ($name=='sd'|| $name=='pls'|| $name=='plw')?"":$rs3[1][3];
    array_splice($kj, 0, 2);
    array_splice($kj, -1, 1);
    $arr['prize'] = $kj;
    return $arr;
}
$type = isset($_GET['type'])?$_GET['type']:"ssq";//彩票类型
$s = isset($_GET['s'])?$_GET['s']:"1";//1是期数,2是数据
$n = isset($_GET['n'])?$_GET['n']:"30";//不传递取30条数据
if(1==$s){
    json(200,'期数查询成功',get_qishu($type,$n),$n);
}else{
    $q = isset($_GET['q'])?$_GET['q']:get_qishu($type,1)[0];//要查询的期数
    json(200,"数据查询成功",get_data($type,$q));
}